// components/sound-record/index.js
// const recorderManager = wx.getRecorderManager()
// const innerAudioContext = wx.createInnerAudioContext()
const $api = require('../../request/api').API;
const app = getApp();
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
Component({
  // styleIsolation: 'shared',
  /**
   * 组件的属性列表
   */
  properties: {
    showRecord: {
      type: Object,
      value: false
    },
    beeperId: {
      type: Object
    },
    btnId: {
      type: Object
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    record: false,
    play: false,
    percentage: 0, // 进度条
    seconds: 0, // 秒数
    endSeconds: 20, // 最终秒数
    timer: false, // 时间定时器
    timer2: false, // 进度条定时器
    temp: 0, //用来分隔时间的，很重要，否则暂停继续的时候误差特别严重
    tempReocrdFile: '' //
    // stop:false,// 是否结束录音
  },
  /**
   * 生命周期
   */
  lifetimes: {
    /**
     * 组件进入页面节点的时候
     */
    attached() {
      this.watchRecord();
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 阻止冒泡
    stopBubble() {},
    // 隐藏录音弹框
    hideRecordPopup() {
      recorderManager.stop();
      innerAudioContext.stop();
      clearInterval(this.data.timer);
      clearInterval(this.data.timer2);
      this.setData({
        play: false,
        record: false,
        showRecord: false,
        seconds: 0,
        percentage: 0,
        temp: 0,
        tempReocrdFile: ''
      });
    },
    // 显示录音弹框
    showRecordPopup() {
      this.setData({
        showRecord: true
      });
    },
    // 监听录音和播放
    watchRecord() {
      // 监听开始录音
      recorderManager.onStart(() => {
        // 开始录音的时候把录音文件清空，并停止播放
        innerAudioContext.stop();
        this.setData({
          tempReocrdFile: ''
        });
        this.recordOperate();
      });
      // 监听暂停录音
      recorderManager.onPause(res => {
        clearInterval(this.data.timer);
        clearInterval(this.data.timer2);
        this.setData({
          record: false
        });
      });
      // 监听继续录音
      recorderManager.onResume(() => {
        this.recordOperate();
      });
      // 监听停止录音
      recorderManager.onStop(res => {
        this.setData({
          tempReocrdFile: this.data.showRecord ? res.tempFilePath : ''
        });
      });
      // 监听播放录音
      innerAudioContext.onPlay(() => {
        this.setData({
          play: true
        });
      });
      // 监听结束录音
      innerAudioContext.onEnded(() => {
        this.setData({
          play: false
        });
      });
    },
    // 开始录音或者继续录音
    recording() {
      this.setData({
        play: false
      });
      // 没有达到20s就继续录音，达到20s就重新开始录音
      if (this.data.seconds > 0 && this.data.seconds < 20) {
        this.resumeRecord();
      } else {
        this.startRecord();
      }
    },
    // 录音时候的页面变化
    recordOperate() {
      clearInterval(this.data.timer);
      clearInterval(this.data.timer2);
      if (this.data.seconds == this.data.endSeconds) {
        this.setData({
          temp: 0,
          percentage: 0,
          seconds: 0
        });
      }

      this.setData({
        record: true
      });
      // 时间定时器
      this.data.timer = setInterval(() => {
        this.setData({
          temp: this.data.temp + 10
        });
        if (this.data.temp >= 1000) {
          this.setData({
            seconds: this.data.seconds + 1,
            temp: 0
          });
        }
        if (this.data.seconds == this.data.endSeconds) {
          this.setData({
            record: false
          });
          clearInterval(this.data.timer);
        }
      }, 10);

      // 进度条定时器
      this.data.timer2 = setInterval(() => {
        this.setData({
          percentage: this.data.percentage + 0.1
        });
        if (this.data.percentage >= 100) clearInterval(this.data.timer2);
      }, this.data.endSeconds);
    },
    // 暂停录音
    pauseRecord() {
      recorderManager.pause();
    },
    // 结束录音
    stopRecord() {
      recorderManager.stop();
      // 先由进度条判断如果进度条为0那么就表示尚未录音
      if (!this.data.percentage) {
        Toast.fail({
          message: '请先录音',
          forbidClick: true
        });
        return;
      }
      clearInterval(this.data.timer);
      clearInterval(this.data.timer2);
      this.setData({
        seconds: 0,
        percentage: 0,
        record: false
      });

      // this.triggerEvent("recordSoundFile",this.data.tempReocrdFile)
    },
    // 继续录音
    resumeRecord() {
      recorderManager.resume();
    },
    //开始录音
    startRecord: function () {
      // var that=this
      const options = {
        duration: 20000, //指定录音的时长，单位 ms
        sampleRate: 16000, //采样率
        numberOfChannels: 1, //录音通道数
        encodeBitRate: 96000, //编码码率
        format: 'mp3', //音频格式，有效值 aac/mp3
        frameSize: 50 //指定帧大小，单位 KB
      };
      //开始录音
      wx.authorize({
        scope: 'scope.record',
        success() {
          console.log('录音授权成功');
          recorderManager.start(options);

          recorderManager.onError(res => {});
        },
        fail() {
          console.log('第一次录音授权失败');
          wx.showModal({
            title: '提示',
            content: '您未授权录音，功能将无法使用',
            showCancel: true,
            confirmText: '授权',
            confirmColor: '#52a2d8',
            success: function (res) {
              if (res.confirm) {
                //确认则打开设置页面（重点）
                wx.openSetting({
                  success: res => {
                    console.log(res.authSetting);
                    if (!res.authSetting['scope.record']) {
                      //未设置录音授权
                      console.log('未设置录音授权');
                      wx.showModal({
                        title: '提示',
                        content: '您未授权录音，功能将无法使用',
                        showCancel: false,
                        success: function (res) {}
                      });
                    } else {
                      //第二次才成功授权
                      // console.log("设置录音授权成功");
                      // that.setData({
                      // status: 2,
                      // })
                      recorderManager.start(options);
                      // recorderManager.onStart(() => {
                      //     that.recordOperate()
                      // console.log('recorder start')
                      // });
                      //错误回调
                      // recorderManager.onError((res) => {
                      // console.log(res);
                      // })
                    }
                  },
                  fail: function () {
                    console.log('授权设置录音失败');
                  }
                });
              } else if (res.cancel) {
                console.log('cancel');
              }
            },
            fail: function () {
              console.log('openfail');
            }
          });
        }
      });
    },
    // 播放录音
    playRecord: function () {
      innerAudioContext.autoplay = true;
      // innerAudioContext.src = this.tempFilePath
      innerAudioContext.src = this.data.tempReocrdFile;
    },
    // 提交订单
    submitOrder() {
      Dialog.confirm({
        title: '提示',
        message: '确认提交订单？'
      })
        .then(() => {
          Toast.loading({
            duration: 0,
            forbidClick: true,
            message: '订单提交中',
            mask: true
          });
          wx.getFileSystemManager().readFile({
            filePath: this.data.tempReocrdFile,
            encoding: 'base64',
            success: res => {
              let params = {
                beeperId: this.data.beeperId,
                audio: res.data
              };
              if (this.data.btnId) {
                params.btnId = this.data.btnId;
              }
              $api
                .voiceAddOrder(params)
                .then(res => {
                  Toast.clear();
                  Toast.success({
                    message: '下单成功',
                    forbidClick: true
                  });
                  setTimeout(() => {
                    this.hideRecordPopup();
                    app.globalData.beeperOrderId = this.data.beeperId;
                    wx.switchTab({
                      url: '/pages/order/index'
                    });
                  }, 2000);
                })
                .catch(err => {
                  Toast.clear();
                  Toast.fail('订单提交失败');
                });
            },
            fail: err => {}
          });
        })
        .catch(() => {});
    },
    // 保存
    saveRecord() {
      wx.getFileSystemManager().readFile({
        filePath: this.data.tempReocrdFile,
        encoding: 'base64',
        success: res => {
          wx.showToast({
            title: '保存成功'
          });
          this.triggerEvent('saveRecord', res.data);
        },
        fail: err => {
          wx.showToast({
            title: '失败'
          });
        }
      });
    }
  }
});
